package com.clps.algorithm.chapter15;

public class demo03_最大岛屿03 {

    public int maxAreaOfIsLang(int[][] grid){
        int rows = grid.length;
        int cols = grid[0].length;

        boolean[][] visited = new boolean[rows][cols];
        int maxArea = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if(grid[i][j] == 1 && !visited[i][j]){
                    int area = getArea(grid,visited,i,j);
                    maxArea = Math.max(maxArea,area);
                }
            }
        }
        return  maxArea;
    }

    private int getArea(int[][] grid, boolean[][] visited, int i, int j) {
        int area = 1;
        visited[i][j] = true;

        int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        for (int[] dir : dirs) {
            int r = i+dir[0];
            int c = j + dir[1];
            if (r >= 0 && r < grid.length
                    && c >= 0 && c < grid[0].length
                    && grid[r][c] == 1 && !visited[r][c]) {
                area += getArea(grid, visited, r, c);
            }
        }

        return  area;
    }
}
